import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread("hanzi1.jpg")
# 将读取后的图片转换为灰度图

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 应用阈值操作将灰度图转换为二值图，这里使用反向二值化
_, binary_image = cv2.threshold(gray_image, 70, 255, cv2.THRESH_BINARY_INV)

# 保存二值化图片
path_to_save_binary_image = "path_to_save_binary_image.jpg"

# 确保图片已经是二值化的，如果不是，你需要先进行二值化处理
binary_img = cv2.imread("path_to_save_binary_image.jpg", cv2.IMREAD_GRAYSCALE)

# 创建腐蚀核，为了提高容错率这里使用2X2的矩形结构元素
kernel = np.ones((9 , 9), np.uint8)

# 应用腐蚀操作
# iterations参数需要调高到一定次数,来确保拼音和噪声点能被尽量消除,此次图片8次,

eroded_img = cv2.erode(binary_img, kernel, iterations=1)

eroded_img = np.rot90(eroded_img, k=-1)  # k=-1 代表顺时针旋转

# 保存腐蚀后的图片,以便观察效果
cv2.imwrite("path_to_save_eroded_image.jpg", eroded_img)

# 定义膨胀操作的结构元素，这里使用矩形
kernel = np.ones((5, 5), np.uint8)

# 应用膨胀操作
dilated_image = cv2.dilate(eroded_img, kernel, iterations=6)

# 应用中值滤波，窗口大小可以根据需要调整
median_filtered_image = cv2.medianBlur(dilated_image, 3)

# ,由于图片是倾斜的所以使用numpy的旋转功能，顺时针旋转90度
#median_filtered_image1 = np.rot90(median_filtered_image, k=2)  # k=-1 代表顺时针旋转

# 保存进行膨胀,中值滤波后的图片

cv2.imwrite("path_to_save_dilated_image.jpg", median_filtered_image)

# 进行闭运算,在这里把迭代参数iterations调到15
closed_img = cv2.morphologyEx(dilated_image, cv2.MORPH_CLOSE, kernel,iterations=15)


# ,由于图片是倾斜的所以使用numpy的旋转功能，顺时针旋转90度
edges_image = np.rot90(closed_img, k=-1)  # k=-1 代表顺时针旋转

# 保存进行膨胀,填充闭合区域后的图片
cv2.imwrite("path_to_save_closed_image.jpg", closed_img)

# 应用Canny边缘检测
edges = cv2.Canny(closed_img, 100, 200)

# ,由于图片是倾斜的所以使用numpy的旋转功能，顺时针旋转90度
#edges_image = np.rot90(edges, k=1)  # k=-1 代表顺时针旋转

# 保存边缘检测,顺时针旋转90度的图片

cv2.imwrite("edges_image.jpg", edges)

# 应用阈值进行二值化
_, binary_img = cv2.threshold(edges, 105, 255, cv2.THRESH_BINARY)

# 寻找连通域
contours, _ = cv2.findContours(binary_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 绘制矩形框
for contour in contours:
    # 计算轮廓的边界框
    x, y, w, h = cv2.boundingRect(contour)

    # 绘制矩形框
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 4)


cv2.imwrite("path_to_save_final_image.jpg", image)

# 显示所有过程的图片

all_image = [gray_image,binary_image,eroded_img,median_filtered_image,closed_img,edges_image]
# 绘制图像
fig, axs = plt.subplots(1, 7,figsize =(20,6))

axs[0].imshow(gray_image,cmap = 'gray')
axs[0].axis('off')
axs[0].set_title('gray_image')

axs[1].imshow(binary_image,cmap = 'gray')
axs[1].axis('off')
axs[1].set_title('binary_image')

axs[2].imshow(eroded_img,cmap = 'gray')
axs[2].axis('off')
axs[2].set_title('eroded_img')

axs[3].imshow(median_filtered_image,cmap = 'gray')
axs[3].axis('off')
axs[3].set_title('median_filtered_image')

axs[4].imshow(closed_img,cmap = 'gray')
axs[4].axis('off')
axs[4].set_title('closed_img')

axs[5].imshow(edges,cmap = 'gray')
axs[5].axis('off')
axs[5].set_title('edges_image')

axs[6].imshow(image,cmap = 'gray')
axs[6].axis('off')
axs[6].set_title('image')

plt.tight_layout()
plt.show()
#
